package com.jiacl.filter;

import org.springframework.stereotype.Service;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by XiaoWei on 2017/10/20.
 */
@Service
@WebFilter(filterName = "loginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("filter 初始化");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String token = (String) request.getAttribute("token");
        Object user = request.getSession().getAttribute("user");
        System.out.println(token);
        System.out.println("过滤");
        chain.doFilter(request,response);
        request.setAttribute("cookie","token=1");
        Cookie token1 = new Cookie("token", "1");
        token1.setMaxAge(3600);
        response.addCookie(token1);
        System.out.println("设置cookie");
    }

    @Override
    public void destroy() {
        System.out.println("destroy 销毁");
    }
}
